<?php
/**
 * 工单类，提供与工单相关的各种方法
 * Created by PhpStorm.
 * User: zhuyujun
 * Date: 2017/10/18
 * Time: 14:25
 */

namespace App\Engine;

use App\Eloquent\Ygt\CustomerOrder;
use Framework\BaseClass\Api\Controller;
use Illuminate\Http\Request;

use App\Eloquent\Ygt\Order;
use App\Eloquent\Ygt\OrderPre;
use App\Eloquent\Ygt\UserMessage;
use App\Eloquent\Ygt\OrderBasic;
use App\Eloquent\Ygt\OrdertypeCategory;
//use App\Eloquent\Ygt\OrderType;
use App\Eloquent\Ygt\OrderDistributionPre;
use App\Eloquent\Ygt\OrderDistribution;
use App\Eloquent\Ygt\OrderProcessPre;
use App\Eloquent\Ygt\OrderProcess;
use App\Eloquent\Ygt\OrderMaterial;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\Message;
use App\Eloquent\Ygt\OrderProcessCourse;
use App\Eloquent\Ygt\OrderMaterialCourse;
use App\Eloquent\Ygt\Privilege;
use App\Eloquent\Ygt\OrderReport;
use App\Eloquent\Ygt\OrderReportType;
use App\Eloquent\Ygt\OrderReportCell;
use App\Eloquent\Ygt\OrderListRelation;
use App\Eloquent\Ygt\OrderFieldCompany;

use App\Eloquent\Ygt\ImgUpload;
use App\Eloquent\Ygt\ProcessFieldRelationSelect;
use App\Eloquent\Ygt\ProcessFieldRelationUnit;
use App\Eloquent\Ygt\ProcessField;

use App\Eloquent\Province;
use App\Eloquent\City;
use App\Eloquent\Area;

//use App\Eloquent\Ygt\Process;
//use App\Eloquent\Ygt\Product;
//use App\Eloquent\Ygt\Permission;
use App\Engine\OrderType;
use App\Engine\Stock;
use App\Engine\Func;
use App\Engine\Product as ProductEngine;
use App\Engine\Permission as PermissionEngine;


use Framework\Services\ImageUpload\imageProcess;

class OrderEngine
{
    /**
     * Description:创建工单-基础页面字段
     * User: zhuyujun
     */
    public function orderBaseFieldList($companyId)
    {
        return OrderFieldCompany::getActiveFieldList($companyId);
//        return [
//            [
//                'field_name' => 'customer_name',
//                'title' => '客户',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'product_name',
//                'title' => '品名',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'contract_number',
//                'title' => '合同编号',
//                'field_type' => 1,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'finished_date',
//                'title' => '交货日期',
//                'field_type' => 7,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'add_distribution_address',
//                'title' => '添加配送地址',
//                'field_type' => 8,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'product_num',
//                'title' => '产品数量',
//                'field_type' => 5,
//                'placeholder' => '请填写',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [
//                    [
//                        'id' => 1,
//                        'title' => '米'
//                    ],
//                    [
//                        'id' => 2,
//                        'title' => '条'
//                    ]
//                ],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'is_priority',
//                'title' => '优先处理',
//                'field_type' => 6,
//                'placeholder' => '',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ],
//            [
//                'field_name' => 'production_case_diagram',
//                'title' => '生产实例图',
//                'field_type' => 9,
//                'placeholder' => '请上传',
//                'new_page_title' => '上传企业图标',
//                'relation_id' => '',
//                'is_must' => 0,
//                'field_unit' => [],
//                'data' => [],
//            ]
//        ];
    }


    //获取工序管理员分派列表
    public function distributionAction($orderTypeId)
    {
        $result = OrderType::getAllStepsWithDistribution($orderTypeId);

        $result->transform(function ($item) {
//            $item->distributionUser = Privilege::getWithDepartmentUser( $item->distribution );
            $distributionUser = DepartmentUser::getWithPrivilege($item->distribution);
            $process_id = $item->process_id;
            $distributionUser->transform(function ($item) use ($process_id) {
                $item->process_id = $process_id;
                $item->ygtUser->avatar = $item->ygtUser->avatar ? Func::getImgUrlById($item->ygtUser->avatar) : asset('upload/appicon/logo.png');
                return $item;
            });
            $item->distributionUser = $distributionUser->toArray();
            return $item;
        });

        $result = $result->filter(function ($item) {
            if ($item->distribution->toArray()) return true;
            return false;
        });
        return $result;
    }

    //确认派发
    public function orderConfirmAssignment($orderId, $assignUser, $userId)
    {
        //获取工单详情
        $tmpOrderObj = Order::where(['id' => $orderId])->first();
        $tmpOrderRow = $tmpOrderObj->toArray();
        $orderTitle = $tmpOrderRow['order_title'];
        $orderTypeId = $tmpOrderRow['order_type'];
        $companyId = $tmpOrderRow['company_id'];
        $foreignKey = intval($tmpOrderRow['customer_order_id']);

        //消息内容需要的
        $orderInfoProductNum    = $tmpOrderObj['product_num'];
        $orderInfoProductNum    = str_replace(',','',$orderInfoProductNum);
        $orderInfoSpecification = $tmpOrderObj['finished_specification'];
        $fieldName23            = $this->changeFieldName23($tmpOrderRow['field_name_23']);
        $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($tmpOrderRow['product_name'],20);

        $messageContent         = "单位名称：{$fieldName23}rnrn品名：{$productName}rnrn";
        $messageContent         .= "成品规格：{$orderInfoSpecification}rnrn数量：{$orderInfoProductNum}rnrn";
        $messageContent         .= "交货日期：{$tmpOrderRow['finished_date']}";

        ////追加功能，给没有设置分派角色的工序增加默认工序管理员（下单人）
        $result = OrderType::getAllStepsWithDistribution($tmpOrderRow['order_type']);
        //获取工序可分派给工序管理员的列表
        $result->transform(function ($item) {
//            $item->distributionUser = Privilege::getWithDepartmentUser( $item->distribution );
            $distributionUser = DepartmentUser::getWithPrivilege($item->distribution);
            $process_id = $item->process_id;
            $distributionUser->transform(function ($item) use ($process_id) {
                $item->process_id = $process_id;
                $item->ygtUser->avatar = $item->ygtUser->avatar ? Func::getImgUrlById($item->ygtUser->avatar) : asset('upload/appicon/logo.png');
                return $item;
            });
            $item->distributionUser = $distributionUser->toArray();
            return $item;
        });

        $noAssignProcessIdList = [];//无需分派的工序id列表
        foreach ($result as $tmpValue) {
            if (empty($tmpValue['distributionUser'])) {
                $noAssignProcessIdList[] = $tmpValue['process_id'];
                //先分配工单给自己
                $orderProcessCollectionList = OrderProcess::where(['order_id' => $orderId, 'process_type' => $tmpValue['process_id']])->get();
                foreach ($orderProcessCollectionList as $orderProcessCollectionRow) {
                    $orderProcessCollectionRow->uid = $tmpOrderRow['uid'];
                    $orderProcessCollectionRow->save();
                }
            }
        }

        //分配用户
        foreach ($assignUser as $assignUserRow) {
            $tmpProcessId = $assignUserRow['process_id'];
            $orderProcess = OrderProcess::firstOrNew(['order_id' => $orderId, 'process_type' => $tmpProcessId]);
            if ($orderProcess->count()) {
                $uid = $assignUserRow['uid'];
                $orderProcess->uid = $uid;
                $orderProcess->save();
            }
        }

        //获取下单人信息
        $userRow = DepartmentUser::getCurrentInfo($tmpOrderRow['uid'])->toArray();

        //获取第一道步骤涉及的工序
        $processFirstList = OrderType::getFirstProcessBag($tmpOrderRow['order_type'])->toArray();
        //获取工单对应的工单工序列表
        $tmpOrderProcessList = OrderProcess::where(['order_id' => $orderId])->get();
        foreach ($tmpOrderProcessList as $tmpOrderProcessRow) {
            //获取工序对应的权限用户
            $processId = $tmpOrderProcessRow['process_type'];
//                $permissionId = Permission::getIdByProcessId($processId);
//                $permissionId = 1;
            if (in_array($tmpOrderProcessRow['process_type'], $processFirstList)) {//给第一道工艺的人发信息
                if (in_array($tmpOrderProcessRow['process_type'], $noAssignProcessIdList)) {//未分派工序管理员，直接分派给员工
                    //获取有提交权限的角色id
                    $privilegeIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderTypeId, $processId, 4); //1:查看;2:可写;3:分配;4:提交;5:转发;
                    //获取角色下的用户id
                    $userList = DepartmentUser::getWithPrivilege($privilegeIds);

                    foreach ($userList as $tmpUserRow) {
                        $tmpUid = $tmpUserRow['user_id'];
                        $orderProcessCourseObj = OrderProcessCourse::firstOrNew(['order_process_id' => $tmpOrderProcessRow['id'], 'uid' => $tmpUid]);
                        $tmpInsertRow = [
                            'uid' => $tmpUid,
                            'total_number' => 0,//自动分派，需完成数量默认为0
                            'order_process_id' => $tmpOrderProcessRow['id'],
                            'assign_id' => $userId,//派发人id
                            'status' => 1,//状态 1-未接单
                            'company_id' => $companyId,//企业Id
                        ];
                        $orderProcessCourseObj->fill($tmpInsertRow);
                        $orderProcessCourseObj->save();
                        $orderPorcessCourseId = $orderProcessCourseObj->id;


                        //发送消息
                        //管理员给员工发消息
                        $userInfo = DepartmentUser::getCurrentInfo($userId)->toArray();
                        $data           = [
                            'company_id'=>$companyId,  'privilege_id'=>'',
                            'form_user_id'=>$userId, 'to_user_id'=>$tmpUid,
                            'foreign_key'=>$foreignKey,
                            'type'=>1,'type_id'=>$orderPorcessCourseId,
                            'title'=>$tmpOrderRow['order_title'],'content'=>$messageContent
                        ];
                        UserMessage::sendCustomerOrderMessage($data);
                        //数据存入

                    }

                    //修改工序工单状态为2（已接单）
                    $tmpOrderProcessRow->status = 2;
                    $tmpOrderProcessRow->save();

                } else {//分派给工序管理员
                    //下单人给管理员发消息
                    $data           = [
                        'company_id'=>$tmpOrderProcessRow['company_id'],  'privilege_id'=>'',
                        'form_user_id'=>$userId, 'to_user_id'=>$tmpOrderProcessRow['uid'],
                        'foreign_key'=>$foreignKey,
                        'type'=>2,'type_id'=>$tmpOrderProcessRow['id'],
                        'title'=>$orderTitle,'content'=>$messageContent
                    ];
                    UserMessage::sendCustomerOrderMessage($data);
                }

                //给此步骤有查看权限的人发消息
                $processId = $tmpOrderProcessRow['process_type'];
                $orderTypeId = $tmpOrderRow['order_type'];
                $privilegeIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderTypeId, $processId, 1);//1:查看;2:可写;3:分配;4:提交;5:转发;
                //批量给所有角色发
                foreach ($privilegeIds as $val) {
                    $data           = [
                        'company_id'=>$tmpOrderProcessRow['company_id'],'privilege_id'=>$val,
                        'form_user_id'=>$userId, 'to_user_id'=>$tmpOrderProcessRow['uid'],
                        'foreign_key'=>$foreignKey,
                        'type'=>9,'type_id'=>$tmpOrderProcessRow['id'],
                        'title'=>$orderTitle,'content'=>$messageContent
                    ];
                    UserMessage::sendCustomerOrderMessage($data);
                }

            }
        }

        //修改工单状态
        $tmpOrderObj->status = 1;
        $tmpOrderObj->save();

        return [
            'code' => 0,
            'msg' => '操作成功'
        ];
    }


    //导入工单列表关联表
    public static function importOrderListRelation($uid = '', $type = '', $companyId = '')
    {
        ////导入主工单
        $where = [];
        $orderList = Order::where($where)->get()->toArray();
        foreach ($orderList as $orderRow){
            $uid = $orderRow['uid'];
            $type = 1;
            $companyId = $orderRow['company_id'];
            $orderTitle = $orderRow['order_title'];
            $orderCreateTime = $orderRow['created_at'];
            $relateId = $orderRow['id'];

            $orderListRelationObj = OrderListRelation::firstOrCreate(['uid'=>$uid,'type'=>$type,'company_id'=>$companyId,'relate_id'=>$relateId]);
            //存入工单列表关联表的信息
            $insertOrderListRelationRow = [];
            $insertOrderListRelationRow['uid'] = $uid;
            $insertOrderListRelationRow['type'] = $type;
            $insertOrderListRelationRow['company_id'] = $companyId;
            $insertOrderListRelationRow['order_title'] = $orderTitle;
            $insertOrderListRelationRow['order_create_time'] = $orderCreateTime;
            $insertOrderListRelationRow['relate_id'] = $relateId;
            $insertOrderListRelationRow['content'] = serialize($orderRow);
            $insertOrderListRelationRow['customer_id'] = $orderRow['customer_name'];
            $insertOrderListRelationRow['plate_id'] = $orderRow['plate_id'];
            $insertOrderListRelationRow['status'] = $orderRow['status'];

            $orderListRelationObj->fill($insertOrderListRelationRow);
            $orderListRelationObj->save();
        }

        ////导入工序工单&&工序工单能查看的人
        //工序管理员查看的工单
        $where = [];
        $orderProcessList = OrderProcess::where($where)->get()->toArray();
        foreach ($orderProcessList as $orderProcessRow){
            $uid = $orderProcessRow['uid'];
            $type = 2;
            $companyId = $orderProcessRow['company_id'];
            $orderCreateTime = $orderProcessRow['created_at'];
            $relateId = $orderProcessRow['id'];
            $orderId = $orderProcessRow['order_id'];

            //获取对应主工单的信息
            $orderRow = Order::where('id',$orderId)->first();
            if(!$orderRow){
                continue;
            }
            $orderRow = $orderRow->toArray();
            $orderTitle = $orderRow['order_title'];




            $orderListRelationObj = OrderListRelation::firstOrCreate(['uid'=>$uid,'type'=>$type,'company_id'=>$companyId,'relate_id'=>$relateId]);
            //存入工单列表关联表的信息
            $insertOrderListRelationRow = [];
            $insertOrderListRelationRow['uid'] = $uid;
            $insertOrderListRelationRow['type'] = $type;
            $insertOrderListRelationRow['company_id'] = $companyId;
            $insertOrderListRelationRow['order_title'] = $orderTitle;
            $insertOrderListRelationRow['order_create_time'] = $orderCreateTime;
            $insertOrderListRelationRow['relate_id'] = $relateId;
            $insertOrderListRelationRow['content'] = serialize($orderRow);
            $insertOrderListRelationRow['customer_id'] = $orderRow['customer_name'];
            $insertOrderListRelationRow['plate_id'] = $orderRow['plate_id'];
            $insertOrderListRelationRow['status'] = $orderProcessRow['status'];

            $orderListRelationObj->fill($insertOrderListRelationRow);
            $orderListRelationObj->save();


            //查看权限的人查看的工单
            //获取该工单有查看权限的用户
            $processId = $orderProcessRow['process_type'];
            $orderTypeId = $orderRow['order_type'];
            $privilegeIds = PermissionEngine::getStepActionPrivilegeIdsByOrderTypeProcess($orderTypeId, $processId, 1);//1:查看;2:可写;3:分配;4:提交;5:转发;
            //获取角色下的用户id
            $userList = DepartmentUser::getWithPrivilege($privilegeIds);
            foreach ($userList as $userRow){
                $seeUid = $userRow['user_id'];

                //其他限制，同一个工单，工序管理员不需要展示查看权限的工单
                if($seeUid == $uid){
                    continue;
                }

                $type = 3;
                $insertOrderListRelationRow['type'] = $type;
                $insertOrderListRelationRow['uid'] = $seeUid;
                $orderListRelationObj = OrderListRelation::firstOrCreate(['uid'=>$uid,'type'=>$type,'company_id'=>$companyId,'relate_id'=>$relateId]);
                $orderListRelationObj->fill($insertOrderListRelationRow);
                $orderListRelationObj->save();
            }
        }

        ////导入员工工单
        $where = [];
        $orderProcessCourseList = OrderProcessCourse::where($where)->get()->toArray();
        foreach ($orderProcessCourseList as $orderProcessCourseRow){
            $uid = $orderProcessCourseRow['uid'];
            $type = 4;
            $companyId = $orderProcessCourseRow['company_id'];
            $orderCreateTime = $orderProcessCourseRow['created_at'];
            $relateId = $orderProcessCourseRow['id'];
            $orderProcessId = $orderProcessCourseRow['order_process_id'];

            //获取工序工单信息&&主工单信息
            $orderProcessRow = OrderProcess::where('id',$orderProcessId)->first();
            if($orderProcessRow){
                $orderProcessRow = $orderProcessRow->toArray();
            }else{
                continue;
            }
            $orderId = $orderProcessRow['order_id'];
            $orderRow = Order::where('id',$orderId)->first()->toArray();
            $orderTitle = $orderRow['order_title'];
            $processId = $orderProcessRow['process_type'];

            //获取工序字段信息（工单列表需要展示前三个）
            //获取工序对应的字段
//            $tmpFieldList = Process::getFieldListByProcessId($processId);
            $count = 0;//计数
            $firstPropertyName = '成品规格';
            $firstPropertyValue = isset($orderRow['finished_specification']) ? $orderRow['finished_specification'] : '';
            $secondPropertyName = '数量';
            $secondPropertyValue = $orderRow['product_num'];
            $thirdPropertyName = '交货日期';
            $thirdPropertyValue = $orderRow['finished_date'];

//            foreach ($tmpFieldList as $tmpFieldRow) {
//                //值转换
//                if ($tmpFieldRow['field_type'] == 5) {//有单位 数量+单位
//                    if ($orderProcessRow[$tmpFieldRow['field_name']]) {
//                        $tmpArr = explode(',', $orderProcessRow[$tmpFieldRow['field_name']]);
//                        $showNum = $tmpArr[0];
//                        if (isset($tmpArr[1])) {
//                            $unitId = $tmpArr[1];
//                        } else {
//                            $unitId = '';
//                        }
//                        $orderProcessRow[$tmpFieldRow['field_name']] = $showNum . ' ' . $unitId;
//                    } else {
//                        $orderProcessRow[$tmpFieldRow['field_name']] = '';
//                    }
//                } elseif ($tmpFieldRow['field_type'] == 6) {//开关
//                    $orderProcessRow[$tmpFieldRow['field_name']] = $orderProcessRow[$tmpFieldRow['field_name']] ? '是' : '否';
//                } elseif ($tmpFieldRow['field_type'] == 4) {//材料选择暂时不显示在
//                    continue;
//                }
//
//                if ($count == 0) {
//                    $firstPropertyName = $tmpFieldRow['title'];
//                    $firstPropertyValue = $orderProcessRow[$tmpFieldRow['field_name']];
//                } elseif ($count == 1) {
//                    $secondPropertyName = $tmpFieldRow['title'];
//                    $secondPropertyValue = $orderProcessRow[$tmpFieldRow['field_name']];
//                } elseif ($count == 2) {
//                    $thirdPropertyName = $tmpFieldRow['title'];
//                    $thirdPropertyValue = $orderProcessRow[$tmpFieldRow['field_name']];
//                } else {
//                    break;
//                }
//                $count++;
//            }

            $orderListRelationObj = OrderListRelation::firstOrCreate(['uid'=>$uid,'type'=>$type,'company_id'=>$companyId,'relate_id'=>$relateId]);
            //存入工单列表关联表的信息
            $insertOrderListRelationRow = [];
            $insertOrderListRelationRow['uid'] = $uid;
            $insertOrderListRelationRow['type'] = $type;
            $insertOrderListRelationRow['company_id'] = $companyId;
            $insertOrderListRelationRow['order_title'] = $orderTitle;
            $insertOrderListRelationRow['order_create_time'] = $orderCreateTime;
            $insertOrderListRelationRow['relate_id'] = $relateId;
            $insertOrderListRelationRow['content'] = serialize($orderRow);
            $insertOrderListRelationRow['customer_id'] = $orderRow['customer_name'];
            $insertOrderListRelationRow['plate_id'] = $orderRow['plate_id'];
            $insertOrderListRelationRow['status'] = $orderProcessCourseRow['status'];

            $orderListRelationObj->fill($insertOrderListRelationRow);
            $orderListRelationObj->save();
        }
    }

    //导入主工单
    public static function importMainOrder($orderRow){
        $uid = $orderRow['uid'];
        $type = 1;
        $companyId = $orderRow['company_id'];
        $orderCreateTime = $orderRow['created_at'];
        $relateId = $orderRow['id'];
        $orderTitle = $orderRow['order_title'];

        $orderListRelationObj = OrderListRelation::firstOrCreate(['uid'=>$uid,'type'=>$type,'company_id'=>$companyId,'relate_id'=>$relateId]);
        //存入工单列表关联表的信息
        $insertOrderListRelationRow = [];
        $insertOrderListRelationRow['uid'] = $uid;
        $insertOrderListRelationRow['type'] = $type;
        $insertOrderListRelationRow['company_id'] = $companyId;
        $insertOrderListRelationRow['order_title'] = $orderTitle;
        $insertOrderListRelationRow['order_create_time'] = $orderCreateTime;
        $insertOrderListRelationRow['relate_id'] = $relateId;
        $insertOrderListRelationRow['content'] = serialize($orderRow);
        $insertOrderListRelationRow['customer_id'] = $orderRow['customer_name'];
        $insertOrderListRelationRow['plate_id'] = $orderRow['plate_id'];
        $insertOrderListRelationRow['status'] = $orderRow['status'];

        $orderListRelationObj->fill($insertOrderListRelationRow);
        $orderListRelationObj->save();
    }

    //导入工序管理员工单
    public static function importProcessManagerOrder($orderProcessRow){
        $uid = $orderProcessRow['uid'];
        $type = 2;
        $companyId = $orderProcessRow['company_id'];
//        $orderCreateTime = $orderProcessRow['created_at'];
        $orderCreateTime = time();//调整为派发时间
        $relateId = $orderProcessRow['id'];
        $orderId = $orderProcessRow['order_id'];

        //获取对应主工单的信息
        $orderRow = Order::where('id',$orderId)->first();
        if(!$orderRow){
            return false;
        }
        $orderRow = $orderRow->toArray();
        $orderTitle = $orderRow['order_title'];

        $orderListRelationObj = OrderListRelation::firstOrCreate(['uid'=>$uid,'type'=>$type,'company_id'=>$companyId,'relate_id'=>$relateId]);
        //存入工单列表关联表的信息
        $insertOrderListRelationRow = [];
        $insertOrderListRelationRow['uid'] = $uid;
        $insertOrderListRelationRow['type'] = $type;
        $insertOrderListRelationRow['company_id'] = $companyId;
        $insertOrderListRelationRow['order_title'] = $orderTitle;
        $insertOrderListRelationRow['order_create_time'] = $orderCreateTime;
        $insertOrderListRelationRow['relate_id'] = $relateId;
        $insertOrderListRelationRow['content'] = serialize($orderRow);
        $insertOrderListRelationRow['customer_id'] = $orderRow['customer_name'];
        $insertOrderListRelationRow['plate_id'] = $orderRow['plate_id'];
        $insertOrderListRelationRow['status'] = $orderProcessRow['status'];

        $orderListRelationObj->fill($insertOrderListRelationRow);
        $orderListRelationObj->save();
    }

    //导入查看工序工单
    public static function importProcessSeeOrder($orderProcessRow,$privilegeIds){
        $uid = $orderProcessRow['uid'];
        $type = 3;
        $companyId = $orderProcessRow['company_id'];
//        $orderCreateTime = $orderProcessRow['created_at'];
        $orderCreateTime = time();//调整为派发时间
        $relateId = $orderProcessRow['id'];
        $orderId = $orderProcessRow['order_id'];

        //其他限制，同一个工单，工序管理员不需要展示查看权限的工单


        //获取对应主工单的信息
        $orderRow = Order::where('id',$orderId)->first();
        if(!$orderRow){
            return false;
        }
        $orderRow = $orderRow->toArray();
        $orderTitle = $orderRow['order_title'];

        //获取角色下的用户id
        $userList = DepartmentUser::getWithPrivilege($privilegeIds);
        foreach ($userList as $userRow){
            $seeUid = $userRow['user_id'];

            //其他限制，同一个工单，工序管理员不需要展示查看权限的工单
            if($seeUid == $uid){
                return false;
            }

            $insertOrderListRelationRow = [];
            $insertOrderListRelationRow['uid'] = $seeUid;
            $insertOrderListRelationRow['type'] = $type;
            $insertOrderListRelationRow['company_id'] = $companyId;
            $insertOrderListRelationRow['order_title'] = $orderTitle;
            $insertOrderListRelationRow['order_create_time'] = $orderCreateTime;
            $insertOrderListRelationRow['relate_id'] = $relateId;
            $insertOrderListRelationRow['content'] = serialize($orderRow);
            $insertOrderListRelationRow['customer_id'] = $orderRow['customer_name'];
            $insertOrderListRelationRow['plate_id'] = $orderRow['plate_id'];
            $insertOrderListRelationRow['status'] = $orderProcessRow['status'];

            $orderListRelationObj = OrderListRelation::firstOrCreate(['uid'=>$uid,'type'=>$type,'company_id'=>$companyId,'relate_id'=>$relateId]);
            $orderListRelationObj->fill($insertOrderListRelationRow);
            $orderListRelationObj->save();
        }
    }

    //导入员工工单
    public static function importProcessCourseOrder($orderProcessCourseRow){
        $uid = $orderProcessCourseRow['uid'];
        $type = 4;
        $companyId = $orderProcessCourseRow['company_id'];
        $orderCreateTime = $orderProcessCourseRow['created_at'];
        $relateId = $orderProcessCourseRow['id'];
        $orderProcessId = $orderProcessCourseRow['order_process_id'];

        //获取工序工单信息&&主工单信息
        $orderProcessRow = OrderProcess::where('id',$orderProcessId)->first()->toArray();
        $orderId = $orderProcessRow['order_id'];
        $orderRow = Order::where('id',$orderId)->first()->toArray();
        $orderTitle = $orderRow['order_title'];
        $processId = $orderProcessRow['process_type'];

        //获取工序字段信息（工单列表需要展示前三个）
        //获取工序对应的字段
//        $tmpFieldList = Process::getFieldListByProcessId($processId);
//        $count = 0;//计数
//        $firstPropertyName = '';
//        $firstPropertyValue = '';
//        $secondPropertyName = '';
//        $secondPropertyValue = '';
//        $thirdPropertyName = '';
//        $thirdPropertyValue = '';
//        foreach ($tmpFieldList as $tmpFieldRow) {
//            //值转换
//            if ($tmpFieldRow['field_type'] == 5) {//有单位 数量+单位
//                if ($orderProcessRow[$tmpFieldRow['field_name']]) {
//                    $tmpArr = explode(',', $orderProcessRow[$tmpFieldRow['field_name']]);
//                    $showNum = $tmpArr[0];
//                    if (isset($tmpArr[1])) {
//                        $unitId = $tmpArr[1];
//                    } else {
//                        $unitId = '';
//                    }
//                    $orderProcessRow[$tmpFieldRow['field_name']] = $showNum . ' ' . $unitId;
//                } else {
//                    $orderProcessRow[$tmpFieldRow['field_name']] = '';
//                }
//            } elseif ($tmpFieldRow['field_type'] == 6) {//开关
//                $orderProcessRow[$tmpFieldRow['field_name']] = $orderProcessRow[$tmpFieldRow['field_name']] ? '是' : '否';
//            } elseif ($tmpFieldRow['field_type'] == 4) {//材料选择暂时不显示在
//                continue;
//            }
//
//            if ($count == 0) {
//                $firstPropertyName = $tmpFieldRow['title'];
//                $firstPropertyValue = $orderProcessRow[$tmpFieldRow['field_name']];
//            } elseif ($count == 1) {
//                $secondPropertyName = $tmpFieldRow['title'];
//                $secondPropertyValue = $orderProcessRow[$tmpFieldRow['field_name']];
//            } elseif ($count == 2) {
//                $thirdPropertyName = $tmpFieldRow['title'];
//                $thirdPropertyValue = $orderProcessRow[$tmpFieldRow['field_name']];
//            } else {
//                break;
//            }
//            $count++;
//        }

        $orderListRelationObj = OrderListRelation::firstOrCreate(['uid'=>$uid,'type'=>$type,'company_id'=>$companyId,'relate_id'=>$relateId]);
        //存入工单列表关联表的信息
        $insertOrderListRelationRow = [];
        $insertOrderListRelationRow['uid'] = $uid;
        $insertOrderListRelationRow['type'] = $type;
        $insertOrderListRelationRow['company_id'] = $companyId;
        $insertOrderListRelationRow['order_title'] = $orderTitle;
        $insertOrderListRelationRow['order_create_time'] = $orderCreateTime;
        $insertOrderListRelationRow['relate_id'] = $relateId;
        $insertOrderListRelationRow['content'] = serialize($orderRow);
//        $insertOrderListRelationRow['content'] = serialize([
//            'order_title' => $orderRow['order_title'],
//            'create_date' => $orderRow['created_at'],
//            'customer_name' => $orderRow['customer_name'],
//            'product_name' => $orderRow['product_name'],
//            'finished_date' => $orderRow['finished_date'],
//            'finished_specification' => $orderRow['finished_specification'],//新增成品规格
//            'finished_date' => $orderRow['finished_date'],
//            'product_num' => $orderRow['product_num'],
//            'production_case_diagram' => $orderRow['production_case_diagram'],//生产示例图
//        ]);
        $insertOrderListRelationRow['customer_id'] = $orderRow['customer_name'];
        $insertOrderListRelationRow['plate_id'] = $orderRow['plate_id'];
        $insertOrderListRelationRow['status'] = $orderProcessCourseRow['status'];

        $orderListRelationObj->fill($insertOrderListRelationRow);
        $orderListRelationObj->save();

    }

    //修改订单状态
    public static function changeOrderListRelationStatus($type,$relateId,$status){
        if($type == 2){//工序工单特殊处理，因为工序管理员工单和查看权限的用户对应的工单是同一个工单
            $where = [];
            $where[]=['relate_id','=',$relateId];
            $whereIn = [2,3];
            $orderListRelationList = OrderListRelation::where($where)->whereIn('type',$whereIn)->get();

        }else{
            $where = [];
            $where[]=['type','=',$type];
            $where[]=['relate_id','=',$relateId];
            $orderListRelationList = OrderListRelation::where($where)->get();
        }

        //修改工单状态
        foreach ($orderListRelationList as $orderListRelationRow){
            $orderListRelationRow->status = $status;
            $orderListRelationRow->save();
        }
    }

    //订单列表-返回type对应的中文提示
    public static function getOrderListRelationTypeStr($type){
        $typeStrArr = [
            '1' => 'mangerDoneCellFunction',//主订单
            '2' => 'productdirectorWaitCellFunction',//工序订单
            '3' => 'productdirectorDoneCellFunction',//工序订单（查看）
            '4' => 'waitCellFunction',//员工订单
        ];
        return $typeStrArr[$type];
    }

    //订单列表-返回type&stauts对应的中文提示
    public static function getOrderListRelationStatusStr($type,$status){
        $statusStrArr = [
            '1' => [
               '1'=>['title'=>'待接单','function_name'=>'mangerDoneCellFunction'],
               '2'=>['title'=>'进行中','function_name'=>'mangerDoneCellFunction'],
               '3'=>['title'=>'已完成','function_name'=>'mangerDoneCellFunction'],
               '4'=>['title'=>'待派单','function_name'=>'mangerDoneCellFunction'],
               '101'=>['title'=>'待开工','function_name'=>'mangerDoneCellFunction'],
            ],
            '2' => [
                '1'=>['title'=>'待接单','function_name'=>'productdirectorWaitCellFunction'],
                '2'=>['title'=>'待派单','function_name'=>'productdirectorWaitCellFunction'],
                '3'=>['title'=>'进行中','function_name'=>'productdirectorproductIngCellFunction'],
                '4'=>['title'=>'已完成','function_name'=>'productdirectorDoneCellFunction'],
                '101'=>['title'=>'待开工','function_name'=>'productdirectorproductIngCellFunction'],
            ],
            '3' => [
                '1'=>['title'=>'待接单','function_name'=>'productdirectorDoneCellFunction'],
                '2'=>['title'=>'待派单','function_name'=>'productdirectorDoneCellFunction'],
                '3'=>['title'=>'进行中','function_name'=>'productdirectorDoneCellFunction'],
                '4'=>['title'=>'已完成','function_name'=>'productdirectorDoneCellFunction'],
                '101'=>['title'=>'待开工','function_name'=>'productdirectorDoneCellFunction'],
            ],
            '4' => [
                '1'=>['title'=>'待接单','function_name'=>'waitCellFunction'],
                '2'=>['title'=>'待领材','function_name'=>'productIngNoneGetFunction'],
                '3'=>['title'=>'进行中','function_name'=>'productIngNoneDoneFunction'],
                '4'=>['title'=>'已完成','function_name'=>'doneCellFunction'],
            ],
        ];
        return $statusStrArr[$type][$status];
    }


    //修改主订单的创建时间（派发时间），作于下单时间使用
    public static function changeMainOrderTime($relateId,$time){
        $type = 1;
        $orderListRelationObj = OrderListRelation::where(['type'=>$type,'relate_id'=>$relateId])->first();

        //存入工单列表关联表的信息
        $orderListRelationObj->order_create_time = $time;
        $orderListRelationObj->save();

    }

    //根据订单id取得该参与该订单的所有员工id
    public static function getCouseIdByOrderId($orderId){
        //获取工单id对应的工序工单id
        $where = ['order_id'=>$orderId];
        $orderProcessIdArr = OrderProcess::where($where)->get()->pluck('id');
        $orderProcessCourseUidArr = OrderProcessCourse::whereIn('order_process_id',$orderProcessIdArr)->get()->pluck('uid');

        return $orderProcessCourseUidArr;
    }

    //工单字段信息转换
    public static function getOrderFiledValueTrue($dataValue,$valFieldType)
    {
        switch ($valFieldType) {
            case 4:
                $resultValue = '';
                //显示每种材料
                $idArr = explode(',', $dataValue);
                $resultValueArr = [];
                foreach ($idArr as $val) {
                    $collection = Product::getProductInfo($val);
                    //考虑集合材料的问题
                    if(strstr($val,'A')){
                        $tmpAssemblageMaterialId = str_replace('A','',$val);
                        $collection = \App\Eloquent\Ygt\AssemblageMaterial::withTrashed()->where(['id'=>$tmpAssemblageMaterialId])->first();
                    }else{
                        $collection = ProductEngine::getProductInfo($val);
                    }

                    if ($collection) {//过滤异常情况
                        $info = $collection->toArray();
                        $resultValueArr[] = $info['product_name'];
                    }
                }
                if (!empty($resultValueArr)) {
                    $resultValue = implode(',', $resultValueArr);
                }
                break;
            case 5:
                //填写+单位选择-去掉逗号
                $resultValue = str_replace(',', '', $dataValue);
                break;
            case 6:
                //开关-转换成是否
                $resultValue = $dataValue ? '是' : '否';
                break;
            case 9:
                //图片
                $productionCaseDiagramIds = isset($dataValue) ? $dataValue : '';
                if ($productionCaseDiagramIds) {
                    $tmpArr = explode(',', $productionCaseDiagramIds);
                    $productionCaseDiagramId = reset($tmpArr);
                    $productionCaseDiagram = ImgUpload::getImgUrlById($productionCaseDiagramId);
                    if (!$productionCaseDiagram) {//未获取到id对应的图片
                        $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
                    }

                } else {
                    $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
                }

                $resultValue = $productionCaseDiagram;
                break;
            case 15:
                //宽长
                $resultValue = '';
                $resultValueArr = explode(',', $dataValue);
                if (!empty($resultValueArr) && (count($resultValueArr) == 2)) {
                    $resultValue = sprintf("宽%s×长%s厘米", $resultValueArr[0], $resultValueArr[1]);
                }
                //如果数据都为空，显示为空
                $hasData = false;
                foreach ($resultValueArr as $tmpValue){
                    if($tmpValue){
                        $hasData = true;
                    }
                }
                if(!$hasData){
                    $resultValue = '';
                }
                break;
            case 16:
                //宽长高
                $resultValue = '';
                $resultValueArr = explode(',', $dataValue);
                if (!empty($resultValueArr) && (count($resultValueArr) == 3)) {
                    $resultValue = sprintf("宽%s×长%s×M边%s厘米", $resultValueArr[0], $resultValueArr[1], $resultValueArr[2]);
                }
                //如果数据都为空，显示为空
                $hasData = false;
                foreach ($resultValueArr as $tmpValue){
                    if($tmpValue){
                        $hasData = true;
                    }
                }
                if(!$hasData){
                    $resultValue = '';
                }
                break;
            case 17:
                //跳版选择
                $resultValue  = '';
                if ($dataValue) {
                    $plateRow = Plate::getPlateInfo($dataValue);
                    if ($plateRow) {
//                        //现在版的名称为品名ID，需要再调整下
//                        $tmpObj = \App\Eloquent\Ygt\BuyersProduct::where(['id'=>$plateRow['plate_name']])->first();
//                        if($tmpObj){
//                            $resultValue = $tmpObj['name'];
//                        }else{
//                            $resultValue = $plateRow['plate_name'];
//                        }
                        $resultValue = $plateRow['plate_no'];
                    }
                }

                break;
            case 18:
                //客户选择
                $resultValue  = '';
                $resultValue = \App\Engine\Customer::getNameById($dataValue);
                if (!$resultValue) {
                    $resultValue = $dataValue;
                }
                break;
            case 19:
                //单位展示
                $resultValue = \App\Engine\Buyers::getNameById($dataValue);
                if (!$resultValue) {
                    $resultValue = $dataValue;
                }
                break;
            case 20:
                //品名展示
                $buyersProduct = \App\Eloquent\Ygt\BuyersProduct::where(['id'=>$dataValue])->first();
                if ($buyersProduct) {
                    $resultValue = $buyersProduct['name'];
                } else {
                    $resultValue = $dataValue;
                }
                break;
            default:
                $resultValue = $dataValue;
        }

        return $resultValue;

    }


    //转变单位名称字段 原因 该字段存值 有三种
    //1单位的id 2单位的名称 3空
    public function changeFieldName23($value='')
    {
        $result         = $value;
        if($value)
        {
            $result     = Buyers::getNameById($value);
            if (!$result) {
                $result = $value;
            }
        }
        return $result;
    }


    //有版时添加版相关的数据到版-工单关联表中
    public static function getOrderPlateField(){
        return [
            'machine' =>
                [
                    'title' => '机台',
                    'field' => '',
                ],
            'membrane ' =>
                [
                    'title' => '膜',
                    'field' =>'field_name_117',
                ],
            'printing_ink' =>
                [
                    'title' => '油墨',
                    'field' =>'',
                ],
            'auxiliary' =>
                [
                    'title' => '助剂',
                    'field' =>'field_name_78',
                ],
        ];
    }

    //获取对应权限是否需要填件
    public static function getPrivilegePiece($privelegeId,$ordertypeProcessId){
        $where = ['process_ordertype_id'=>$ordertypeProcessId,'privilege_id'=>$privelegeId,'type'=>3];
        $needPieceRow = \App\Eloquent\Ygt\FieldLimit::where($where)->first();
        if($needPieceRow){
            if($needPieceRow->limits){
                return true;
            }
        }

        return false;
    }

    //获取对应权限能否成品入库
    public static function getPrivilegeFinishedProduct($privelegeId,$ordertypeProcessId){
        $where = ['process_ordertype_id'=>$ordertypeProcessId,'privilege_id'=>$privelegeId,'type'=>4];
        $finishedProductRow = \App\Eloquent\Ygt\FieldLimit::where($where)->first();
        if($finishedProductRow){
            if($finishedProductRow->limits){
                return true;
            }
        }

        return false;
    }

    //获取对应权限是否不进行工序数量统计
    public static function getProcessNumNoStatistics($privelegeId){
        $needPiecePrivilegeIds = [150];
        if(in_array($privelegeId,$needPiecePrivilegeIds)){
            return true;
        }else{
            return false;
        }
    }

    //获取uid对应的客户ID
    public static function getCustomerIdByUid($uid){
        $where = ['user_id' => $uid];
        $customerId = '';
        $customerObj = \App\Eloquent\Ygt\Customer::where($where)->first();
        if($customerObj){
            $customerId = $customerObj->id;
        }

        return $customerId;
    }

    //获取对应工序是否不显示金额相关数据
    public static function getHideMoneyDataByProcessId($processId){
        $isHideMoneydata = \App\Eloquent\Ygt\Process::getOneValueById($processId, 'is_hide_moneydata');
        if(!$isHideMoneydata){
            return 1;
        }else{
            return 0;
        }
    }

    //获取员工的计件工资
    public static function getEmployeePieceWage($orderProcessId,$privilegeId,$orderProcessCourseId){
        //先判断有没有批量设置角色计件工资
        $tmpOrderWage = '';
        $tmpOrderProcessId = $orderProcessId;
        $tmpOrderWageObj = \App\Eloquent\Ygt\OrderWage::where(['order_process_id'=>$tmpOrderProcessId,'privilege_id'=>$privilegeId])->first();
        if($tmpOrderWageObj){
            $tmpOrderWage = $tmpOrderWageObj->piece_wage;
        }

        //设置在个人上的计件工资优先级更高
        $tmpOrderWageObj = \App\Eloquent\Ygt\OrderWage::where(['order_process_course_id'=>$orderProcessCourseId])->first();
        if($tmpOrderWageObj){
            $tmpOrderWage = $tmpOrderWageObj->piece_wage;
        }

        return $tmpOrderWage;
    }

    //获取订单对应的价格
    public static function getCustomerOrderPriceById($customerOrderId){
        $customerOrderPriceObj = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id'=>$customerOrderId])->first();
        if($customerOrderPriceObj){
            if(isset($customerOrderPriceObj->deal_price)){
                return $customerOrderPriceObj->deal_price;
            }
        }
        return false;
    }

    //获取工序中选择的材料
    public static function getProcessMaterialIdList($orderProcessId){
        $orderProcessRow = \App\Eloquent\Ygt\OrderProcess::where(['id'=>$orderProcessId])->first()->toArray();

        $processFieldList = \App\Eloquent\Ygt\Process::getFieldListByProcessId($orderProcessRow['process_type']);
        $returnMaterialList = [];
        foreach ($processFieldList as $processFieldRow) {
            $tmpFiledType = \App\Eloquent\Ygt\ProcessField::getFieldTypeByFieldName($processFieldRow['field_name'], $orderProcessRow['company_id']);
            if ($tmpFiledType == 4) {//材料选择暂时不显示在
                $materialList = explode(',', $orderProcessRow[$processFieldRow['field_name']]);
                foreach ($materialList as $materialId){
                    if($materialId){
                        $returnMaterialList[] = $materialId;
                    }
                }
            }
        }

        return $returnMaterialList;
    }


    //修改订单状态
    public static function changeCustomerOrderStatus($customerOrderId,$changeStatus){
        $tmpObj = \App\Eloquent\Ygt\CustomerOrder::where(['id'=>$customerOrderId])->first();
        if($tmpObj){
            $tmpObj->fill(['status'=>$changeStatus]);
            $tmpObj->save();
            return true;
        }
        return false;
    }

    /**
     * Description:获取节点对应拥有该权限的角色
     * User: zhuyujun
     * @param $companyId
     * @param $appnodeId
     * $appnodeId ：
     * 1-跳转到我的工单页面 -- 下单人权限
     * 2-？ -- 已弃用
     * 3-库存管理 -- 仓库权限
     * 4-主管向员工派单 -- 工序管理员权限
     * 7-添加新材料消息 -- 仓库权限（会受到添加新材料的消息）
     * 8-工单材料采购 --
     * 9-厂长权限 -- 厂长权限（可以查看所有人）
     * 10-采购员权限 -- 采购员权限(表示对应角色是采购员)
     * 11-财务权限
     * 12-发货员权限
     * 13-销售员权限
     * 14-发货员权限
     * 15-发货员权限
     */

    public static function getPrivilegeByNode($companyId,$appnodeId){
        return\App\Eloquent\Ygt\Privilege::getPrivilegeIds( $companyId, $appnodeId );
    }

    /*
     * 获取指定时间内员工姓名,工单数,累计数量,工资金额
     *
     * 参数
     *   年,月,厂id
     * 返回结果
     *   厂下员工在该月内的
     *   员工姓名,工单数,累计数量,工资金额
     * */
    public static function getCompanyStaffWorkInfo($companyId,$startTime,$endTime){
        $startTimeStamp = strtotime($startTime);
        $endTimeStamp = strtotime($endTime);
        //获取指定企业指定时间区间内所有员工工单
        $where = [];
        $where[] = ['company_id','=',$companyId];
        $where[] = ['submit_time','>=',$startTimeStamp];
        $where[] = ['submit_time','<=',$endTimeStamp];
        $orderProcessCourseGradationList = \App\Eloquent\Ygt\OrderProcessCourseGradation::where($where)->get();

        $workInfoList = [];
        foreach ($orderProcessCourseGradationList as $orderProcessCourseGradationRow){
            $tmpOrderProcessCourseRow =  \App\Eloquent\Ygt\OrderProcessCourse::where(['id'=>$orderProcessCourseGradationRow['order_process_course_id']])->first();
            $tmpOrderProcessRow = \App\Eloquent\Ygt\OrderProcess::where(['id'=>$tmpOrderProcessCourseRow['order_process_id']])->first();

            //获取员工姓名,角色
            $tmpUserInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($tmpOrderProcessCourseRow['uid'])->toArray();

            //获取员工计件工资
            $tmpUserWage = self::getEmployeePieceWage($tmpOrderProcessCourseRow['order_process_id'],$tmpUserInfo['privilege_id'],$tmpOrderProcessCourseRow['id']);

            //获取工单数，累计数量，工资金额
            if(!isset($workInfoList[$tmpOrderProcessCourseRow['uid']])){
                $workInfoList[$tmpOrderProcessCourseRow['uid']]['uid'] = $tmpUserInfo['user_id'];
                $workInfoList[$tmpOrderProcessCourseRow['uid']]['true_name'] = $tmpUserInfo['truename'];
                $workInfoList[$tmpOrderProcessCourseRow['uid']]['order_id_list'][] = $tmpOrderProcessRow['order_id'];
                $workInfoList[$tmpOrderProcessCourseRow['uid']]['order_num'] = 1;
                $workInfoList[$tmpOrderProcessCourseRow['uid']]['submit_num'] = $orderProcessCourseGradationRow['submit_num'];
                $workInfoList[$tmpOrderProcessCourseRow['uid']]['wages'] = $tmpUserWage*$orderProcessCourseGradationRow['submit_num'];
            }else{
                $workInfoList[$tmpOrderProcessCourseRow['uid']]['submit_num'] += $orderProcessCourseGradationRow['submit_num'];
                $workInfoList[$tmpOrderProcessCourseRow['uid']]['wages'] += $tmpUserWage*$orderProcessCourseGradationRow['submit_num'];
                if(!in_array($tmpOrderProcessRow['order_id'],$workInfoList[$tmpOrderProcessCourseRow['uid']]['order_id_list'])){
                    $workInfoList[$tmpOrderProcessCourseRow['uid']]['order_id_list'][] = $tmpOrderProcessRow['order_id'];
                    $workInfoList[$tmpOrderProcessCourseRow['uid']]['order_num'] ++;
                }
            }
        }

        return $workInfoList;
    }

    /*
     * 获取指定时间内员工的工单
     *
     * 参数
     *   厂id,用户id(员工id),开始时间,结束时间
     * 返回结果
     *   该员工的这段时间内的工单
     *
     * */
    public static function getStaffOrderList($companyId,$userId,$startTime,$endTime){
        $startTimeStamp = strtotime($startTime);
        $endTimeStamp = strtotime($endTime);
        //获取指定企业指定时间区间内所有员工工单
        $where = [];
        $where[] = ['company_id','=',$companyId];
        $where[] = ['uid','=',$userId];
        $where[] = ['submit_time','>=',$startTimeStamp];
        $where[] = ['submit_time','<=',$endTimeStamp];
        $orderProcessCourseIdList = \App\Eloquent\Ygt\OrderProcessCourseGradation::where($where)->get()->pluck('order_process_course_id');
        $orderProcessIdList = \App\Eloquent\Ygt\OrderProcessCourse::whereIn('id',$orderProcessCourseIdList)->get()->pluck('order_process_id');
        $orderIdList = \App\Eloquent\Ygt\OrderProcess::whereIn('id',$orderProcessIdList)->get()->pluck('order_id');
        $orderList = \App\Eloquent\Ygt\Order::whereIn('id',$orderIdList)->get()->toArray();

        $tmpOrderList = [];
        foreach ($orderList as $tmpOrderRow) {
            if (isset($tmpOrderRow['product_num'])) {
                $tmpArr = explode(',', $tmpOrderRow['product_num']);
                $tmpOrderRow['product_num'] = '';
                foreach ($tmpArr as $tmpValue) {
                    $tmpOrderRow['product_num'] .= $tmpValue;
                }
            }

            //成品规格数据处理
            if (isset($tmpOrderRow['finished_specification'])) {
                $tmpArr = explode(',', $tmpOrderRow['finished_specification']);
                if (count($tmpArr) == 2) {
                    $tmpOrderRow['finished_specification'] = sprintf("%s×%s厘米", $tmpArr[0], $tmpArr[1]);
                }

                if (count($tmpArr) == 3) {
                    $tmpOrderRow['finished_specification'] = sprintf("%s×%s×%s厘米", $tmpArr[0], $tmpArr[1], $tmpArr[2]);
                }

                //如果数据都为空，显示为空
                $hasData = false;
                foreach ($tmpArr as $tmpValue) {
                    if ($tmpValue) {
                        $hasData = true;
                    }
                }

                if (!$hasData) {
                    $tmpOrderRow['finished_specification'] = '';
                }
            }

            //单位名称显示处理
            if (isset($tmpOrderRow['field_name_23'])) {
                $baseId = $tmpOrderRow['field_name_23'];
                $showTitle = \App\Engine\Buyers::getNameById($tmpOrderRow['field_name_23']);
                if (!$showTitle) {
                    $showTitle = $tmpOrderRow['field_name_23'];
                }
                $tmpOrderRow['field_name_23'] = $showTitle;
            }

            //获取生产实例图
            $productionCaseDiagramIds = isset($tmpOrderRow['production_case_diagram']) ? $tmpOrderRow['production_case_diagram'] : '';
            if ($productionCaseDiagramIds) {
                $tmpArr = explode(',', $productionCaseDiagramIds);
                $productionCaseDiagramId = reset($tmpArr);
                $productionCaseDiagram = \App\Eloquent\Ygt\ImgUpload::getImgUrlById($productionCaseDiagramId);
                if (!$productionCaseDiagram) {//未获取到id对应的图片
                    $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
                }

            } else {
                $productionCaseDiagram = env('APP_URL') . '/assets/mobile/common/images/order_list_default.png';
            }

            //订单创建时间（派发时间）
            $orderCreateTime = $tmpOrderRow['created_at'];
            if ($orderCreateTime) {
                $orderCreateTime = date('Y-m-d', $orderCreateTime);
                if ($orderCreateTime < 631152000) {//过滤1970的情况
                    $orderCreateTime = '';
                }
            } else {
                $orderCreateTime = '';
            }

            //获取工序类型名称
            $orderTypeTitle = \App\Engine\OrderType::getOneValueById($tmpOrderRow['order_type'], 'title');

            //获取工单状态
            $status = $tmpOrderRow['status'];
            $orderStatusStr = '';
            $orderStatusColor = 'FFB401';
            if ($status == 1) {//待接单
                $orderStatusStr = '待接单';
                $orderStatusColor = 'FFB401';

            } elseif ($status == 101) {//待开工
                $orderStatusStr = '待开工';
                $orderStatusColor = 'FFB401';
            } elseif ($status == 2) {//生产中
                $orderStatusStr = '生产中';
                $orderStatusColor = 'FE7E57';
            } elseif ($status == 3) {//已完工
                $orderStatusStr = '已完成';
                $orderStatusColor = '04C9B3';
            }


            $productName = \App\Engine\OrderEngine::getOrderFiledValueTrue($tmpOrderRow['product_name'],20);
            $tmpOrderList[] = [
                'ordertype_title' => '工艺:',//工单列表展示字段
                'order_title' => '单号:',//工单列表展示字段
                'unit_name' => isset($tmpOrderRow['field_name_23']) ? $tmpOrderRow['field_name_23'] : '',//新加字段单位
                'product_name' => isset($productName) ? $productName : '',//新加字段品名
                'order_title_value' => $tmpOrderRow['order_title'],//新加字段单号
                'firstPropertyName' => '成品规格',
                'secondPropertyName' => '数量',
                'thirdPropertyName' => '交货日期',
                'thirdPropertyValue' => $tmpOrderRow['finished_date'],
                'secondPropertyValue' => $tmpOrderRow['product_num'],
                'firstPropertyValue' => isset($tmpOrderRow['finished_specification']) ? $tmpOrderRow['finished_specification'] : '',
                'productionCaseDiagram' => $productionCaseDiagram,
                'productOrderTimeValue' => $orderCreateTime,
                'orderTypeTitle' => $orderTypeTitle,
                'relate_id' => $tmpOrderRow['id'],
                'orderStatus' => $orderStatusStr,
                'statusColor' => $orderStatusColor,
            ];
        }

        $orderList = $tmpOrderList;
        return $orderList;
    }


    //处理订单中特殊的字段
    public static function dealOrderFiled($orderRow){
        //处理产品数量
        if (isset($orderRow['product_num'])) {
            $tmpArr = explode(',', $orderRow['product_num']);
            $orderRow['product_num'] = '';
            foreach ($tmpArr as $tmpValue) {
                if($tmpValue && ($tmpValue != 'null') ){
                    $orderRow['product_num'] .= $tmpValue;
                }
            }
        }

        //成品规格数据处理
        if (isset($orderRow['finished_specification'])) {
            $tmpArr = explode(',', $orderRow['finished_specification']);
            if (count($tmpArr) == 2) {
                $orderRow['finished_specification'] = sprintf("%s×%s厘米", $tmpArr[0], $tmpArr[1]);
            }

            if (count($tmpArr) == 3) {
                $orderRow['finished_specification'] = sprintf("%s×%s×%s厘米", $tmpArr[0], $tmpArr[1], $tmpArr[2]);
            }

            //如果数据都为空，显示为空
            $hasData = false;
            foreach ($tmpArr as $tmpValue) {
                if ($tmpValue) {
                    $hasData = true;
                }
            }

            if (!$hasData) {
                $orderRow['finished_specification'] = '';
            }
        }

        //单位名称显示处理
        if (isset($orderRow['field_name_23'])) {
            $baseId = $orderRow['field_name_23'];
            $showTitle = \App\Engine\Buyers::getNameById($orderRow['field_name_23']);
            if (!$showTitle) {
                $showTitle = $orderRow['field_name_23'];
            }
            $orderRow['field_name_23'] = $showTitle;
        }

        //品名处理 20180626 zhuyujun
        $buyersProduct = \App\Eloquent\Ygt\BuyersProduct::where(['id'=>$orderRow['product_name']])->first();
        if ($buyersProduct) {
            $orderRow['product_name'] = $buyersProduct['name'];
        }
        //工艺名称
        $orderTypeTitle = '';
        if(isset($orderRow['order_type']))
        {
            $orderTypeTitle     = \App\Eloquent\Ygt\OrderType::getOneValueById($orderRow['order_type'],'title');
        }
        $orderRow['order_type_title'] = $orderTypeTitle;

        return $orderRow;
    }

    //获取工单对应的订单议定价格 20180728 zhuyujun
    public static function getOrderPrice($orderId){
        //获取订单ID
        $customerOrderId = \App\Eloquent\Ygt\Order::where(['id'=>$orderId])->first()->customer_order_id;

        //获取订单的议定价格
        if($customerOrderId){
            $customerOrderPriceRow = \App\Eloquent\Ygt\CustomerOrderPrice::where(['customer_order_id'=>$customerOrderId])->first();
            if($customerOrderPriceRow){
                $price =$customerOrderPriceRow->deal_price;

                if(!$price){
                    //如果没有议定价格，获取销售员报价
                    $price =$customerOrderPriceRow->sale_price;
                }
                return $price;
            }

        }
        return false;
    }


    //获取工艺需完成的数量（单位不一致的时候，通过片料规格进行计算）
    public static function getOrderPorcessNeedNum($processId,$orderRow){
        $processRow = \App\Eloquent\Ygt\Process::where(['id'=>$processId])->first();

        $productNum = 0;
        $tmpArr = explode(',', $orderRow['product_num']);
        if(isset($tmpArr[0]) && $tmpArr[0] ){
            $productNum = $tmpArr[0];
        }

        if($processRow['is_same_unit']){
            return $productNum;
        }else{
            //通过片料规格的长，计算比例
            if($orderRow['chip_specification_length']){
                $tmpArr = explode(',', $orderRow['chip_specification_length']);
                if(isset($tmpArr[1]) && $tmpArr[1] ){
                    return $tmpArr[1]*$productNum/100;
                }
            }

            return $productNum;
        }
    }

    //获取某个工艺的完成数量
    public static function getOrderPorcessCompleteNum($orderProcessRow){
        $processRow = \App\Eloquent\Ygt\Process::getInfo(['id'=>$orderProcessRow['process_type']]);
        $processIsSum = $processRow['is_sum'];//工序数量是否累加 0-不累加 1-累加
        $orderProcessCourseList = \App\Eloquent\Ygt\OrderProcessCourse::where(['order_process_id' => $orderProcessRow['id']])->get();
        $preFinishNum = 0;

        $finishUserNumList = [];
        foreach ($orderProcessCourseList as $orderProcessCourseRow) {

            //设定的角色不进行统计数量到工序数量中
            //过滤异常数据
            if (!\App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])) {
                continue;
            }
            $tmpUserInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
            $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
            if (\App\Engine\OrderEngine::getProcessNumNoStatistics($tmpPrivilegeId)) {
                continue;
            }

            $preFinishNum += $orderProcessCourseRow['finish_number'];
            if (!$processIsSum) {//不累加
                $tmpUserInfo = DepartmentUser::getCurrentInfo($orderProcessCourseRow['uid'])->toArray();
                $tmpPrivilegeId = $tmpUserInfo['privilege_id'];
                if (isset($finishUserNumList[$tmpPrivilegeId])) {
                    $finishUserNumList[$tmpPrivilegeId]['finish_number'] += $orderProcessCourseRow['finish_number'];
                } else {
                    $finishUserNumList[$tmpPrivilegeId]['finish_number'] = $orderProcessCourseRow['finish_number'];
                }
            }
        }

        //不累加--未完工时取完成量最小的员工
        if (!empty($finishUserNumList)) {
            $finishMinNum = '';
            foreach ($finishUserNumList as $finishUserNumRow) {
                if ($finishMinNum === 0) {//如果有员工完成数量为0，
                    break;
                }

                if ($finishUserNumRow['finish_number'] < $finishMinNum || $finishMinNum === '') {//如果有员工完成数量更少，或者第一个员工的数据
                    $finishMinNum = $finishUserNumRow['finish_number'];
                }
            }
            $preFinishNum = $finishMinNum;
        }

        return $preFinishNum;
    }

    //获取工单相关进度条对应的类型
    public static function getOrderRadioType($radio){
        if($radio == 0){
            return 1;
        }elseif($radio > 0 && $radio <1){
            return 2;
        }elseif($radio >= 1){
            return 3;
        }
    }


    //工单详情获取版的详情
    public static function getOrderPlateDealInfo($tmpCreateOrderPlateRowContent,$processFieldTitle){
        $re = [];
        /**固定版**/
        $fixedPlateShow = "";
        if(!empty($tmpCreateOrderPlateRowContent['branch']['fixed_plate'])){
            //按排序值排序
            array_multisort(array_column($tmpCreateOrderPlateRowContent['branch']['fixed_plate'],'sort'),SORT_ASC,$tmpCreateOrderPlateRowContent['branch']['fixed_plate']);
        }

        foreach ($tmpCreateOrderPlateRowContent['branch']['fixed_plate'] as $tmpFixedPlate){
            $fixedPlateShow .= $tmpFixedPlate['name'].',';
        }

        if(!$fixedPlateShow){
            $fixedPlateShow = '无';
        }else{
            $fixedPlateShow = substr($fixedPlateShow,0,-1);
            $fixedPlateShow = "【固定版】".$fixedPlateShow;
        }

        $re[] = [
            '$leftLabelValue' => $processFieldTitle,
            '$rightLabelValue' => $fixedPlateShow,
        ];


        /**套版**/
        if(isset($tmpCreateOrderPlateRowContent['branch']['colourplate'])){
            $isFirst = true;
            foreach ($tmpCreateOrderPlateRowContent['branch']['colourplate'] as $tmpColourplate){
                $tmpColourplateShow = "";
                if(isset($tmpColourplate['group'])){
                    if(!empty($tmpColourplate['group'])){
                        foreach ($tmpColourplate['group'] as $tmpGroupRow){
                            $tmpColourplateShow .= $tmpGroupRow['name'].' '.$tmpGroupRow['model'].',';
                        }
                    }else{
                        $tmpColourplateShow = '';
                    }

                }

                if($tmpColourplateShow){
                    $tmpColourplateShow = substr($tmpColourplateShow,0,-1);
                }


                if(!$tmpColourplateShow){
                    $tmpColourplateShow = "({$tmpColourplate['num']})".'【无套版组合】';
                }else{
//                                $tmpColourplateShow = "【套版组合】".$tmpColourplateShow."：".$tmpColourplate['num'];
                    $tmpColourplateShow = "({$tmpColourplate['num']})"."【套版组合】".$tmpColourplateShow;
                }


                $re[] = [
//                    '$leftLabelValue' => $processFieldTitle,
                    '$leftLabelValue' => '',
                    '$rightLabelValue' => $tmpColourplateShow,
                ];


            }
        }

        /**其他版**/
        if(isset($tmpCreateOrderPlateRowContent['branch']['other_plate'])){
            foreach ($tmpCreateOrderPlateRowContent['branch']['other_plate'] as $tmpOtherPlate){
                $tmpOtherPlateShow = $tmpOtherPlate['name'];
                if(!$tmpOtherPlateShow){
                    $tmpOtherPlateShow = '无';
                    continue;
                }else{
//                                $tmpOtherPlateShow = "【套版】".$tmpColourplateShow."：".$tmpColourplateShow['num'];
                    $tmpOtherPlateShow = "({$tmpOtherPlate['num']})"."【套版】".$tmpOtherPlate['name'];
                }


                $re[] = [
//                    '$leftLabelValue' => $processFieldTitle,
                    '$leftLabelValue' => '',
                    '$rightLabelValue' => $tmpOtherPlateShow,
                ];
            }
        }


        return $re;
    }

    //获取版信息中的套版ID和型号ID
    public static function getOrderPlateInfoDealId($tmpCreateOrderPlateRowContent){
        $plateId = $tmpCreateOrderPlateRowContent['plate_id'];
        $plateName = $tmpCreateOrderPlateRowContent['plate_name'];

        $plateBranchId = "";
        $plateBranchColourplateId = "";
        $plateModelName = "";

        $plateBranchIdArr = [];
        $plateBranchColourplateIdArr = [];
        //固定版
        foreach ($tmpCreateOrderPlateRowContent['branch']['fixed_plate'] as $tmpFixedPlate) {
            //获取固定版对应的ID
            $tmpPlateBranchRow = \App\Eloquent\Ygt\PlateBranch::where(['plate_id'=>$plateId, 'type' => 1, 'name' => $tmpFixedPlate['name']])->first();
            if ($tmpPlateBranchRow) {
                $plateBranchIdArr[] = $tmpPlateBranchRow['id'];
            }
        }

        //套版
        if(isset($tmpCreateOrderPlateRowContent['branch']['colourplate'])){
            $isFirst = true;
            foreach ($tmpCreateOrderPlateRowContent['branch']['colourplate'] as $tmpColourplate){
                $tmpColourplateShow = "";
                if(isset($tmpColourplate['group'])){
                    if(!empty($tmpColourplate['group'])){
                        foreach ($tmpColourplate['group'] as $tmpGroupRow){
//                            $tmpColourplateShow .= $tmpGroupRow['name'].' '.$tmpGroupRow['model'].',';
                            $plateModelName .= $tmpGroupRow['name'].' '.$tmpGroupRow['model'].' ';
                            $tmpPlateBranchRow = \App\Eloquent\Ygt\PlateBranch::where(['plate_id'=>$plateId, 'type' => 2, 'name' => $tmpGroupRow['name']])->first();
                            if ($tmpPlateBranchRow) {
                                $plateBranchIdArr[] = $tmpPlateBranchRow['id'];
                                $tmpPlateBranchColourplateRow = \App\Eloquent\Ygt\PlateBranchColourplate::where(['plate_branch_id'=>$tmpPlateBranchRow['id'], 'name' => $tmpGroupRow['model']])->first();
                                if($tmpPlateBranchColourplateRow){
                                    $plateBranchColourplateIdArr [] = $tmpPlateBranchColourplateRow['id'];
                                }
                            }
                        }
                    }
                }
            }
        }

        /**其他版**/
        if(isset($tmpCreateOrderPlateRowContent['branch']['other_plate'])){
            foreach ($tmpCreateOrderPlateRowContent['branch']['other_plate'] as $tmpOtherPlate){
                $plateModelName .= $tmpOtherPlate['name'] ." ";

                $tmpPlateBranchRow = \App\Eloquent\Ygt\PlateBranch::where(['plate_id'=>$plateId, 'type' => 3, 'name' => $tmpOtherPlate['name']])->first();
                if ($tmpPlateBranchRow) {
                    $plateBranchIdArr[] = $tmpPlateBranchRow['id'];
                }
            }
        }

        if(!empty($plateBranchIdArr)){
            $plateBranchId = implode(',',$plateBranchIdArr);
        }
        if(!empty($plateBranchColourplateIdArr)){
            $plateBranchColourplateId = implode(',',$plateBranchColourplateIdArr);
        }

        return [
            'plateBranchId' => $plateBranchId,
            'plateBranchColourplateId' => $plateBranchColourplateId,
            'plateName' => $plateName,
            'plateModelName' => $plateModelName,
        ];
    }


    //按指定需求，处理数组中的指定字段
    //$input 包含要处理数据的数组
    //$field_name 要处理的字段名称
    //$type  处理的类型
    //$extra_info_field_name 处理后添加的额外信息 在input的字段名
    static public function handleInput($input,$field_name,$type,$extra_info_field_name){
        switch($type){
            case 4://材料类型
                $input = self::handleMaterialInput($input,$field_name,$extra_info_field_name);
                break;
            default:
                break;
        }


        return $input;
    }

    static public function handleMaterialInput($input,$field_name,$extra_info_field_name){
        if(isset($input[$field_name])){
            //新结构 包含数据
            if(strstr($input[$field_name],'is_purchase')){
                $tempArr = json_decode(htmlspecialchars_decode($input[$field_name]),true);
                if($tempArr){
                    $tempIdArr = [];
                    foreach($tempArr as $val){
                        $tempIdArr[] = $val['id'];
                    }
                    $input[$field_name] = implode(',',$tempIdArr);
                    if(isset($input[$extra_info_field_name])){
                        $input[$extra_info_field_name]= array_merge($input[$extra_info_field_name],$tempArr);
                    }
                    else{
                        $input[$extra_info_field_name] = $tempArr;
                    }
                }
            }
            //老的 或者新的格式空数组
//            else{
//                $tempArr = json_decode(htmlspecialchars_decode($input[$field_name]),true);
//                //转成功  且为空数组
//                if(!$tempArr){
//                    $input[$field_name] = '';
//                }
//            }
        }
        return $input;
    }
}